package com.heima.bos.shiro;

import java.util.List;

import javax.annotation.Resource;

import org.apache.poi.hssf.record.chart.TickRecord;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import com.heima.bos.dao.FunctionDaoInter;
import com.heima.bos.dao.UserDaoInter;
import com.heima.bos.domain.Function;
import com.heima.bos.domain.User;

public class BOSRealm extends AuthorizingRealm{
	@Resource
	private UserDaoInter userDao;
	@Resource
	private FunctionDaoInter functionDao;
	//先认证
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
			throws AuthenticationException {
		System.out.println(3333);
		UsernamePasswordToken tokenUser = (UsernamePasswordToken) token;
		String username = tokenUser.getUsername();
		char[] password = tokenUser.getPassword();
		List<User> list = userDao.findByNameQuery("findUserByUsername", username);
		if(list == null || list.size() == 0){
			return null;
		}
		User user = list.get(0);
		SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, user.getPassword(), this.getClass().getName());
		return info;
	}
	//再授权
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection paramPrincipalCollection) {
		System.out.println("start");
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		//获取当前用户
		User user = (User) paramPrincipalCollection.getPrimaryPrincipal();
		String username = user.getUsername();
		//管理员
		if(username.equals("wangwei")){
			List<Function> list = functionDao.findAll();
			for (Function function : list) {
				info.addStringPermission(function.getCode());
			}
		}else{//一般用户
			List<Function> list = functionDao.findByUserId(user.getId());
			for (Function function : list) {
				info.addStringPermission(function.getCode());
			}
		}
		System.out.println("end");
//		info.addStringPermission("staff");
		return info;
	}

}
